using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PushStone : MonoBehaviour
{
    public Material materialChoose;
    Renderer render;
    Material materialOri;
    bool choose;
    PlayerController player;
    Rigidbody rig;
    AudioSource audioSource;
    CanMoveBlock canMove;

    private void Awake()
    {
        rig = GetComponent<Rigidbody>();
        player = FindObjectOfType<PlayerController>();
        render = transform.GetChild(0).GetComponent<Renderer>();
        materialOri = render.material;
        audioSource = GetComponent<AudioSource>();
        canMove = GetComponent<CanMoveBlock>();
    }

    private void OnDestroy()
    {
        player.stoneFalling = false;
    }

    private void Update()
    {
        if (LevelManager.ChooseBlock == gameObject && !LevelManager.instance.cameraMoving)
        {
            ChooseThis();
        }
        else
        {
            DontChooseThis();
        }
        if (rig.linearVelocity.y > 0) rig.linearVelocity = Vector3.zero;
        if(Input.GetMouseButtonUp(0) && choose)
        {
            //player.PushStone(FindStoneSidePos(), transform);
        }
    }

    public void PlayAudio()
    {
        audioSource.time = 0.1f;
        audioSource.Play();
    }

    public void UseGravity()
    {
        rig.useGravity = true;
        StartCoroutine(StoneFallCor());
    }

    IEnumerator StoneFallCor()
    {
        yield return new WaitForSeconds(0.2f);

        while(true)
        {
            if (rig.linearVelocity.y < -0.1f)
            {
                player.stoneFalling = true;
            }
            else
            {
                player.stoneFalling = false;
                rig.useGravity = false;
                canMove.FindStander();
                break;
            }
            yield return null;
        }
    }

    void ChooseThis()
    {
        render.material = materialChoose;
        choose = true;
    }

    void DontChooseThis()
    {
        render.material = materialOri;
        choose = false;
    }

    Vector3 FindStoneSidePos()
    {
        Vector3 dir = (player.transform.position - transform.position).normalized;
        float r = Vector3.Dot(dir, Vector3.right);
        float l = Vector3.Dot(dir, Vector3.left);
        float f = Vector3.Dot(dir, Vector3.forward);
        float b = Vector3.Dot(dir, Vector3.back);
        float max = Mathf.Max(r, l, f, b);

        if(Mathf.Abs(max-r)<0.01f)
        {
            return transform.position + Vector3.right*3;
        }
        else if(Mathf.Abs(max - l) < 0.01f)
        {
            return transform.position + Vector3.left*3;
        }
        else if (Mathf.Abs(max - f) < 0.01f)
        {
            return transform.position + Vector3.forward*3;
        }
        else
        {
            return transform.position + Vector3.back*3;
        }
    }

    public Vector3 GetStoneSpeed()
    {
        return rig.linearVelocity;
    }
}
